document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const statusMessage = document.getElementById('status-message');
  const modeOptions = document.querySelectorAll('input[name="mode"]');
  
  // 手动跳过相关元素
  const skipFromMinInput = document.getElementById('skip-from-min');
  const skipFromSecInput = document.getElementById('skip-from-sec');
  const skipToMinInput = document.getElementById('skip-to-min');
  const skipToSecInput = document.getElementById('skip-to-sec');
  const setSkipRangeBtn = document.getElementById('set-skip-range');
  
  // 直接跳转相关元素
  const jumpToMinInput = document.getElementById('jump-to-min');
  const jumpToSecInput = document.getElementById('jump-to-sec');
  const setJumpBtn = document.getElementById('set-jump');
  
  // 自定义规则相关元素
  const ruleFromMinInput = document.getElementById('rule-from-min');
  const ruleFromSecInput = document.getElementById('rule-from-sec');
  const ruleToMinInput = document.getElementById('rule-to-min');
  const ruleToSecInput = document.getElementById('rule-to-sec');
  const addRuleBtn = document.getElementById('add-rule');
  
  const customRulesList = document.getElementById('custom-rules');
  const skippedSegmentsList = document.getElementById('skipped-segments');

  // 速度控制相关元素
  const speedButtons = {
    '2x': document.getElementById('speed-2x'),
    '4x': document.getElementById('speed-4x'),
    '8x': document.getElementById('speed-8x'),
    '16x': document.getElementById('speed-16x'),
    'toggle': document.getElementById('toggle-speed')
  };
  
  let currentMode = 'manual';
  let hasVideo = false;
  let customRules = [];
  let skippedSegments = [];
  let currentTabId = null;
  let speedControlActive = false;
  let currentSpeed = 1;
  
  // 获取当前激活标签页的ID
  chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
    if (tabs && tabs.length > 0) {
      currentTabId = tabs[0].id;
      console.log('当前标签页ID:', currentTabId);
      
      // 加载保存的设置
      loadSettings();
      
      // 检查当前标签页是否有视频
      checkForVideo(currentTabId);
    } else {
      statusMessage.textContent = '无法获取当前标签页';
      statusMessage.style.color = '#F44336';
    }
  });
  
  // 检查标签页中是否有视频
  function checkForVideo(tabId) {
    try {
      statusMessage.textContent = '正在检测视频...';
      statusMessage.style.color = '#FFA500';
      
      // 首先通过后台脚本检查
      chrome.runtime.sendMessage({
        action: 'checkVideoInTab',
        tabId: tabId
      }, function(response) {
        if (chrome.runtime.lastError) {
          console.error('检查视频时出错:', chrome.runtime.lastError);
          statusMessage.textContent = '检测视频失败: ' + chrome.runtime.lastError.message;
          statusMessage.style.color = '#F44336';
          return;
        }
        
        console.log('检查视频响应:', response);
        
        if (response && response.hasVideo) {
          hasVideo = true;
          statusMessage.textContent = '已检测到视频';
          statusMessage.style.color = '#4CAF50';
        } else if (response && response.error) {
          statusMessage.textContent = '检测视频出错: ' + response.error;
          statusMessage.style.color = '#F44336';
        } else {
          // 备用方法：直接向内容脚本发送消息
          tryDirectContentScriptMessage(tabId);
        }
      });
    } catch (error) {
      console.error('检查视频时发生异常:', error);
      statusMessage.textContent = '检测视频失败: ' + error.message;
      statusMessage.style.color = '#F44336';
    }
  }
  
  // 尝试直接向内容脚本发送消息
  function tryDirectContentScriptMessage(tabId) {
    try {
      chrome.tabs.sendMessage(tabId, { action: 'findVideo' }, function(response) {
        if (chrome.runtime.lastError) {
          console.error('直接消息失败:', chrome.runtime.lastError);
          statusMessage.textContent = '未检测到视频';
          statusMessage.style.color = '#F44336';
          return;
        }
        
        if (response && response.hasVideo) {
          hasVideo = true;
          statusMessage.textContent = '已检测到视频';
          statusMessage.style.color = '#4CAF50';
        } else {
          statusMessage.textContent = '未检测到视频';
          statusMessage.style.color = '#F44336';
        }
      });
    } catch (error) {
      console.error('直接消息时发生异常:', error);
      statusMessage.textContent = '未检测到视频';
      statusMessage.style.color = '#F44336';
    }
  }

  // 加载保存的设置
  function loadSettings() {
    chrome.storage.local.get(['mode', 'customRules', 'skippedSegments'], function(result) {
      if (chrome.runtime.lastError) {
        console.error('加载设置出错:', chrome.runtime.lastError);
        return;
      }
      
      if (result.mode) {
        currentMode = result.mode;
        document.querySelector(`input[name="mode"][value="${currentMode}"]`).checked = true;
      }
      
      if (result.customRules) {
        customRules = result.customRules;
        renderCustomRules();
      }
      
      if (result.skippedSegments) {
        skippedSegments = result.skippedSegments;
        renderSkippedSegments();
      }
    });
  }

  // 保存设置
  function saveSettings() {
    chrome.storage.local.set({
      mode: currentMode,
      customRules: customRules,
      skippedSegments: skippedSegments
    }, function() {
      if (chrome.runtime.lastError) {
        console.error('保存设置失败:', chrome.runtime.lastError);
      } else {
        console.log('设置已保存');
      }
    });
  }

  // 将分钟和秒转换为总秒数
  function convertToSeconds(minutes, seconds) {
    const mins = parseFloat(minutes) || 0;
    const secs = parseFloat(seconds) || 0;
    return mins * 60 + secs;
  }
  
  // 将总秒数转换为分钟和秒的对象
  function convertToMinutesAndSeconds(totalSeconds) {
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = Math.floor(totalSeconds % 60);
    return { minutes, seconds };
  }
  
  // 格式化时间为 MM:SS 格式
  function formatTime(minutes, seconds) {
    const mins = minutes || 0;
    const secs = seconds || 0;
    return `${mins}:${secs < 10 ? '0' + secs : secs}`;
  }

  // 更新工作模式
  modeOptions.forEach(function(option) {
    option.addEventListener('change', function() {
      currentMode = this.value;
      saveSettings();
      
      // 将模式通知到内容脚本
      if (currentTabId) {
        sendMessageToTab(currentTabId, { 
          action: 'setMode', 
          mode: currentMode 
        });
      }
    });
  });

  // 设置跳过范围
  setSkipRangeBtn.addEventListener('click', function() {
    if (!hasVideo || !currentTabId) {
      alert('未检测到视频或标签页无效');
      return;
    }
    
    const fromMin = parseFloat(skipFromMinInput.value) || 0;
    const fromSec = parseFloat(skipFromSecInput.value) || 0;
    const toMin = parseFloat(skipToMinInput.value) || 0;
    const toSec = parseFloat(skipToSecInput.value) || 0;
    
    const fromTotalSeconds = convertToSeconds(fromMin, fromSec);
    const toTotalSeconds = convertToSeconds(toMin, toSec);
    
    if (fromTotalSeconds >= toTotalSeconds) {
      alert('请输入有效的时间范围（结束时间必须大于开始时间）');
      return;
    }
    
    sendMessageToTab(currentTabId, { 
      action: 'skipRange', 
      from: fromTotalSeconds,
      to: toTotalSeconds,
      isRule: true // 标记为规则，而不是立即跳转
    }, function(response) {
      if (response && response.success) {
        // 添加到已跳过列表
        const segment = { 
          from: { minutes: fromMin, seconds: fromSec }, 
          to: { minutes: toMin, seconds: toSec }, 
          type: '手动跳过规则' 
        };
        skippedSegments.push(segment);
        renderSkippedSegments();
        saveSettings();
        
        // 清空输入
        skipFromMinInput.value = '';
        skipFromSecInput.value = '';
        skipToMinInput.value = '';
        skipToSecInput.value = '';
        
        // 提示用户
        alert('跳过规则设置成功！当视频播放到指定时间段时将自动跳过。');
      } else if (response && response.error) {
        alert('跳过规则设置失败: ' + response.error);
      }
    });
  });

  // 设置跳转
  setJumpBtn.addEventListener('click', function() {
    if (!hasVideo || !currentTabId) {
      alert('未检测到视频或标签页无效');
      return;
    }
    
    const jumpToMin = parseFloat(jumpToMinInput.value) || 0;
    const jumpToSec = parseFloat(jumpToSecInput.value) || 0;
    const jumpToTotalSeconds = convertToSeconds(jumpToMin, jumpToSec);
    
    if (jumpToTotalSeconds < 0) {
      alert('请输入有效的时间点');
      return;
    }
    
    sendMessageToTab(currentTabId, { 
      action: 'jumpTo', 
      time: jumpToTotalSeconds
    }, function(response) {
      if (response && response.success) {
        // 清空输入
        jumpToMinInput.value = '';
        jumpToSecInput.value = '';
        
        // 添加到已跳过列表
        const segment = { 
          from: null, // 没有起始点，表示直接跳转
          to: { minutes: jumpToMin, seconds: jumpToSec }, 
          type: '直接跳转' 
        };
        skippedSegments.push(segment);
        renderSkippedSegments();
        saveSettings();
      } else if (response && response.error) {
        alert('跳转失败: ' + response.error);
      }
    });
  });

  // 添加自定义规则
  addRuleBtn.addEventListener('click', function() {
    const fromMin = parseFloat(ruleFromMinInput.value) || 0;
    const fromSec = parseFloat(ruleFromSecInput.value) || 0;
    const toMin = parseFloat(ruleToMinInput.value) || 0;
    const toSec = parseFloat(ruleToSecInput.value) || 0;
    
    const fromTotalSeconds = convertToSeconds(fromMin, fromSec);
    const toTotalSeconds = convertToSeconds(toMin, toSec);
    
    if (fromTotalSeconds >= toTotalSeconds) {
      alert('请输入有效的时间范围（结束时间必须大于开始时间）');
      return;
    }
    
    const rule = { 
      from: { minutes: fromMin, seconds: fromSec },
      to: { minutes: toMin, seconds: toSec },
      fromSeconds: fromTotalSeconds,
      toSeconds: toTotalSeconds
    };
    
    customRules.push(rule);
    renderCustomRules();
    saveSettings();
    
    // 将规则通知到内容脚本
    if (currentTabId) {
      sendMessageToTab(currentTabId, { 
        action: 'updateCustomRules', 
        rules: customRules
      });
    }
    
    // 清空输入
    ruleFromMinInput.value = '';
    ruleFromSecInput.value = '';
    ruleToMinInput.value = '';
    ruleToSecInput.value = '';
  });

  // 安全地向标签页发送消息
  function sendMessageToTab(tabId, message, callback) {
    try {
      chrome.tabs.sendMessage(tabId, message, function(response) {
        if (chrome.runtime.lastError) {
          console.error('向标签页发送消息失败:', chrome.runtime.lastError);
          if (callback) callback({ error: chrome.runtime.lastError.message });
        } else {
          if (callback) callback(response);
        }
      });
    } catch (error) {
      console.error('发送消息出错:', error);
      if (callback) callback({ error: error.message });
    }
  }

  // 渲染自定义规则列表
  function renderCustomRules() {
    customRulesList.innerHTML = '';
    
    if (customRules.length === 0) {
      customRulesList.innerHTML = '<div class="empty-list">暂无自定义规则</div>';
      return;
    }
    
    customRules.forEach(function(rule, index) {
      const ruleItem = document.createElement('div');
      ruleItem.className = 'rule-item';
      
      const fromMinutes = rule.from.minutes || 0;
      const fromSeconds = rule.from.seconds || 0;
      const toMinutes = rule.to.minutes || 0;
      const toSeconds = rule.to.seconds || 0;
      
      const ruleText = document.createElement('span');
      ruleText.textContent = `从 ${formatTime(fromMinutes, fromSeconds)} 到 ${formatTime(toMinutes, toSeconds)}`;
      
      const deleteBtn = document.createElement('button');
      deleteBtn.className = 'delete-btn';
      deleteBtn.textContent = 'X';
      deleteBtn.addEventListener('click', function() {
        customRules.splice(index, 1);
        renderCustomRules();
        saveSettings();
        
        // 更新内容脚本中的规则
        if (currentTabId) {
          sendMessageToTab(currentTabId, { 
            action: 'updateCustomRules', 
            rules: customRules
          });
        }
      });
      
      ruleItem.appendChild(ruleText);
      ruleItem.appendChild(deleteBtn);
      customRulesList.appendChild(ruleItem);
    });
  }

  // 渲染已跳过片段列表
  function renderSkippedSegments() {
    skippedSegmentsList.innerHTML = '';
    
    if (skippedSegments.length === 0) {
      skippedSegmentsList.innerHTML = '<div class="empty-list">暂无已跳过片段</div>';
      return;
    }
    
    skippedSegments.forEach(function(segment, index) {
      const segmentItem = document.createElement('div');
      segmentItem.className = 'skipped-item';
      
      let segmentText;
      if (segment.from === null) {
        // 直接跳转
        const toMinutes = segment.to.minutes || 0;
        const toSeconds = segment.to.seconds || 0;
        segmentText = document.createElement('span');
        segmentText.textContent = `跳转到 ${formatTime(toMinutes, toSeconds)} (${segment.type})`;
      } else {
        // 从A跳到B
        const fromMinutes = segment.from.minutes || 0;
        const fromSeconds = segment.from.seconds || 0;
        const toMinutes = segment.to.minutes || 0;
        const toSeconds = segment.to.seconds || 0;
        segmentText = document.createElement('span');
        segmentText.textContent = `从 ${formatTime(fromMinutes, fromSeconds)} 到 ${formatTime(toMinutes, toSeconds)} (${segment.type})`;
      }
      
      const deleteBtn = document.createElement('button');
      deleteBtn.className = 'delete-btn';
      deleteBtn.textContent = 'X';
      deleteBtn.addEventListener('click', function() {
        skippedSegments.splice(index, 1);
        renderSkippedSegments();
        saveSettings();
      });
      
      segmentItem.appendChild(segmentText);
      segmentItem.appendChild(deleteBtn);
      skippedSegmentsList.appendChild(segmentItem);
    });
  }

  // 初始化速度控制按钮事件
  function initSpeedControls() {
    // 设置速度按钮点击事件
    Object.entries(speedButtons).forEach(([speed, button]) => {
      if (speed === 'toggle') {
        button.addEventListener('click', toggleSpeedControl);
      } else {
        const speedValue = parseInt(speed);
        button.addEventListener('click', () => setPlaybackSpeed(speedValue));
      }
    });
  }
  
  // 设置播放速度
  function setPlaybackSpeed(speed) {
    if (!hasVideo || !currentTabId) {
      alert('未检测到视频或标签页无效');
      return;
    }
    
    sendMessageToTab(currentTabId, {
      action: 'setPlaybackSpeed',
      speed: speed
    }, function(response) {
      if (response && response.success) {
        currentSpeed = speed;
        updateSpeedButtonStates();
      } else if (response && response.error) {
        alert('设置播放速度失败: ' + response.error);
      }
    });
  }
  
  // 切换速度控制状态
  function toggleSpeedControl() {
    if (!hasVideo || !currentTabId) {
      alert('未检测到视频或标签页无效');
      return;
    }
    
    sendMessageToTab(currentTabId, {
      action: 'toggleSpeedControl'
    }, function(response) {
      if (response && response.success) {
        speedControlActive = response.active;
        updateSpeedButtonStates();
      } else if (response && response.error) {
        alert('切换速度控制失败: ' + response.error);
      }
    });
  }
  
  // 更新速度按钮状态
  function updateSpeedButtonStates() {
    // 更新速度按钮状态
    Object.entries(speedButtons).forEach(([speed, button]) => {
      if (speed === 'toggle') {
        button.classList.toggle('active', speedControlActive);
      } else {
        const speedValue = parseInt(speed);
        button.classList.toggle('active', speedControlActive && currentSpeed === speedValue);
      }
    });
  }

  // 初始化
  document.addEventListener('DOMContentLoaded', function() {
    // ... existing code ...
    
    // 初始化速度控制
    initSpeedControls();
    
    // ... existing code ...
  });
}); 